<template>
  <el-card style="width: 100%">
    <el-button type="primary" icon="Plus" @click="addTrademard">
      添加品牌
    </el-button>

    <el-table border style="margin: 10px 0" :data="records">
      <el-table-column
        label="序号"
        width="100px"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column
        label="品牌名称"
        align="center"
        prop="tmName"
      ></el-table-column>
      <el-table-column label="品牌LOGO" align="center">
        <template #default="{ row }">
          <img :src="row.logoUrl" width="100px" @click="lookLogo(row)" />
          <el-dialog v-model="row.dialogVisible" :append-to-body="true">
            <img
              w-full
              alt="Preview Image"
              style="width: 100%; height: 100%"
              :src="row.logoUrl"
            />
          </el-dialog>
        </template>
      </el-table-column>
      <el-table-column label="品牌操作" align="center">
        <template #default="{ row }">
          <el-button
            type="warning"
            size="small"
            icon="Edit"
            @click="editTrademard(row)"
          ></el-button>
          <el-popconfirm
            :title="`你确认要删除${row.tmName}吗?`"
            width="250px"
            icon="Delete"
            :hide-after="0"
            @confirm="confirmDelete(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @current-change="getTrademarkInfo"
      @size-change="sizeChange"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :background="true"
      layout="sizes, prev, pager, next, ->, jumper, total"
      :total="total"
    />
  </el-card>

  <el-dialog
    v-model="dialogFormVisible"
    :title="formInfo.id ? '修改品牌' : '添加品牌'"
    width="500"
  >
    <el-form :model="formInfo" :rules="rules" ref="formRef">
      <el-form-item label="品牌名称" :label-width="100" prop="tmName">
        <el-input placeholder="请输入品牌名称" v-model="formInfo.tmName" />
      </el-form-item>
      <el-form-item label="品牌LOGO" :label-width="100" prop="logoUrl">
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="formInfo.logoUrl" :src="formInfo.logoUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confrim">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  reqAddOrUpdateTrademark,
  reqHasTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import { Records, type TradeMark } from '@/api/product/trademark/type.ts'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
let formInfo = ref<TradeMark>({
  id: undefined,
  tmName: '',
  logoUrl: '',
})
let formRef = ref()
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  formInfo.value.logoUrl = response.data
  //图片上传成功,清除掉对应图片校验结果
  formRef.value.clearValidate('logoUrl')
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 4) {
    ElMessage.error('Avatar picture size can not exceed 4MB!')
    return false
  }
  return true
}

let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)
let dialogFormVisible = ref(false)
let records = ref<Records>([])

//品牌自定义校验规则方法
const validatorTmName = (_rule: any, value: any, callBack: any) => {
  //是当表单元素触发blur时候,会触发此方法
  //自定义校验规则
  if (value.trim().length >= 2) {
    callBack()
  } else {
    //校验未通过返回的错误的提示信息
    callBack(new Error('品牌名称位数大于等于两位'))
  }
}
//品牌LOGO图片的自定义校验规则方法
const validatorLogoUrl = (_rule: any, value: any, callBack: any) => {
  //如果图片上传
  if (value) {
    callBack()
  } else {
    callBack(new Error('LOGO图片务必上传'))
  }
}

//表单校验规则对象
const rules = reactive({
  tmName: [
    //required:这个字段务必校验,表单项前面出来五角星
    //trigger:代表触发校验规则时机[blur、change]
    { required: true, trigger: 'change', validator: validatorTmName },
  ],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
})

async function getTrademarkInfo(pager = 1) {
  currentPage.value = pager
  let result = await reqHasTrademark(currentPage, pageSize)
  if (result.code === 200) {
    total.value = result.data.total
    records.value = result.data.records
  }
}

async function confirmDelete(id: number) {
  let result = await reqDeleteTrademark(id)
  if (result.code === 200) {
    ElMessage.success('删除成功')
    getTrademarkInfo(
      records.value.length > 1 || currentPage.value === 1
        ? currentPage.value
        : currentPage.value - 1,
    )
  } else {
    ElMessage.error(result.data)
  }
}
function sizeChange() {
  getTrademarkInfo()
}

onMounted(() => {
  getTrademarkInfo()
})

function addTrademard() {
  dialogFormVisible.value = true
  // 	重置该表单项，将其值重置为初始值，并移除校验结果
  formInfo.value.id = 0
  formInfo.value.tmName = ''
  formInfo.value.logoUrl = ''
  formRef.value.resetFields()
}

function editTrademard(row: TradeMark) {
  dialogFormVisible.value = true
  Object.assign(formInfo.value, row)
  formRef.value.clearValidate('logoUrl')
  formRef.value.clearValidate('tmName')
}

async function confrim() {
  await formRef.value.validate()
  // 将收集到的表单数据发送请求
  let result = await reqAddOrUpdateTrademark(formInfo.value)
  if (result.code === 200) {
    getTrademarkInfo(currentPage.value)
    ElMessage.success(formInfo.value.id ? '修改品牌成功' : '添加品牌成功')
  } else {
    ElMessage.error(formInfo.value.id ? '修改品牌失败' : '添加品牌失败')
  }
  dialogFormVisible.value = false
}

function lookLogo(row: any) {
  row.dialogVisible = true
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
